<template>
    <div>
        <a-drawer
                title=""
                size="default"
                :closable="false"
                :open="open"
                width="420"
                @close="onclose"
                body-style="padding:12px 0px;background-color:#eeeeec"
        >
            <template #extra>
            </template>
            <div>
                <div class="header" ref="header">
                    <div class="headerText">用户健康档案</div>
                    <img class="settingHeaderLine" src="../assets/version2.0/settingHeaderLine.png" alt="">
                </div>
                <a-input v-model:value="userCodeFilter" placeholder="输入用户编码" class="userCodeInput"
                         @focus="openKey"></a-input>
                <a-button class="userCodeSearchBtn">搜索</a-button>
                <a-table
                        :columns="columns"
                        :data-source="filterData"
                        :pagination="ipagination"
                        @change="handleTableChange"
                        @cancel="onclose"
                        style="    margin-top: -20px;"
                >
                    <template #bodyCell="{ column,record }">
                        <template v-if="column.key === 'operation'" >
                            <a @click="openUserFile(record.card_number,record.id)">详情</a>
                            <a-divider type="vertical"></a-divider>
                            <a @click="delUser(record.card_number,record.id)">删除</a>
                        </template>
                    </template>
                </a-table>

                <div class="backDiv" @click="onclose">
                    <BackButton ref="backButton" @click="onclose"></BackButton>
                </div>
            </div>
        </a-drawer>
        <key-board ref="key" :get-key-board-input="getKey" :open="keyBoard" @closeKeyBoard="closeKey"></key-board>
        <user-file ref="userFile"></user-file>
    </div>
</template>

<script>
import axios from "axios";
import API_BASE_URL from "../../config.js";
import UserFile from "@/components/userFile.vue";
import {message} from "ant-design-vue";
import store from "@/store";
import KeyBoard from "@/components/keyBoard.vue";
import BackButton from "@/components/BackButton.vue";

export default {
    name: "usersFile",
    components: {BackButton, KeyBoard, UserFile},
    data() {
        return {
            open: false,
            keyBoard: false,
            userCodeFilter: '',
            //分页参数
            ipagination: {
                current: 1,
                pageSize: 5,
                showTotal: (total, range) => {
                    return range[0] + "-" + range[1] + " 共" + total + "条"
                },
                total: 0
            },
            columns: [
                {
                    title: '用户编码',
                    dataIndex: 'card_number',
                    key: 'card_number'
                },
                {
                    title: '时间',
                    dataIndex: 'created_at',
                    key: 'created_at'
                },
                {
                    title: '操作',
                    key: 'operation',
                },
            ],
            dataSource: [],
            url: {
                userList: "http://api.cgi-gz.com/store-testing-users?page=1&per_page=10",
                user: "http://api.cgi-gz.com/store-testing-users",
                delUser:`${API_BASE_URL}/delete-user`
            }
        }
    },
    methods: {
        openKey(){
            this.keyBoard = true
        },
        closeKey(){
            this.keyBoard = false
            console.log(this.keyBoard)
        },
        getKey(val) {
            this.userCodeFilter = val
        },
        handleTableChange(pagination, filters, sorter) {
            //分页、排序、筛选变化时触发
            //TODO 筛选
            console.log(pagination)
            this.ipagination = pagination;
            this.getUserList();
        },
        //获取用户列表
        getUserList() {
            axios({
                url: this.url.userList,
                method: 'get',
                params: {
                    page: 1,
                    per_page: 10,
                    sort: 'desc'
                },
                headers:{
                    'Authorization': store.state.token
                }
            }).then((res) => {
                let originData = res.data.data.list
                function addObjectsToArray(obj, targetArray) {
                    // 遍历对象的属性
                    for (const key in obj) {
                        if (Object.hasOwnProperty.call(obj, key)) {
                            const value = obj[key];
                            // 检查属性值是否是对象
                            if (typeof value === 'object') {
                                // 如果是对象，将其添加到目标数组中
                                targetArray.push(value);
                            }
                        }
                    }
                    return targetArray;
                }
                this.dataSource=[]
                addObjectsToArray(originData, this.dataSource)
            })
        },
        //打开用户个人档案
        openUserFile(userCode, id) {
            this.$refs.userFile.openUser = true
            this.$refs.userFile.userCode = userCode
            this.$refs.userFile.userId = id
            console.log("userID", id)
            console.log("userCode", userCode)
            axios({
                url: this.url.user,
                method: 'get',
                params: {
                    page: 1,
                    per_page: 10,
                    key:userCode
                },
                headers:{
                    'Authorization': store.state.token
                }
            }).then((res) => {
                let list = res.data.data.list
                console.log('list',list)
                console.log('list[0]',list[0])
                console.log('list[0].created_at',list[0].created_at)
                console.log('list[0].id',list[0].id)
                let dataSource = []
                for (let i=0;i<list.length;i++) {
                    let temp = {}
                    temp['created_at'] = list[i].created_at
                    temp['id'] = list[i].id
                    dataSource.push(temp);
                }
                this.$refs.userFile.dataSource = dataSource
                console.log("用户个人档案", this.$refs.userFile.dataSource)
            })
        },
        delUser(userCode,id){
            if(userCode===store.state.rootUserCode||id===store.state.rootId){
                message.error("无法删除管理员账户")
            } else if(userCode===store.state.userCode){
                message.error("无法删除当前用户，请先选择其他用户，再删除此用户")
            }
            else{
                axios({
                    url:this.url.delUser,
                    method:'get',
                    params:{
                        card_number:userCode
                    }
                }).then((res)=>{
                    this.dataSource=[]
                    this.handleTableChange()
                    message.success("删除用户"+userCode+"成功")
                })
            }

        },
        onclose() {
            this.open = false
            this.openwifiList = false
            this.dataSource = []
            store.commit('setUserFile', {value: false})
        },
    },
    computed: {
        filterData() {
            return this.dataSource.filter(user => {
                return user.card_number.indexOf(this.userCodeFilter) !== -1
            })
        }
    },
    mounted() {
    },
    created() {
        if (store.state.sendRequest){
            this.getUserList()
        }
    },
}
</script>

<style scoped>
.header{
    justify-content: center;
}
.headerText{
    display: flex;
    justify-content: center;
    font-size: 18px;
    font-weight: bold;
}
.settingHeaderLine{
    width: 420px;
    height: 9px;
    position: relative;
}

.userCodeInput {
    font-weight: 1000;
    margin-bottom: 13px;
    border-radius: 30px;
    padding-left: 20px;
    padding-top: 2px;
    padding-bottom: 2px;
    height: 40px;
    margin-top: 20px;
    width: 367px;
    margin-left: 20px;
}

.userCodeSearchBtn {
    position: relative;
    border-radius: 30px;
    height: 40px;
    padding-top: 2px;
    background-color: #f39700;
    width: 100px;
    font-size: 16px;
    bottom: 53px;
    left: 287px;
}

.backDiv{
    position: relative;
    justify-content: center;
    display: flex;
    margin-top: 20px;
    margin-bottom: 20px;
}
</style>